package com.cunyu.action;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.tom.kit.StringUtil;
import com.cunyu.bean.Muser;
import com.cunyu.util.HttpUtil;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.AsyncClientHttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import cn.tom.kit.io.FileUtil;
import com.cunyu.listener.Constants;
import com.cunyu.listener.RequestContext;
import com.cunyu.service.MuserService;

@Controller
public class IndexController extends OpenController {

	@Resource
	MuserService muserService;

	@RequestMapping("/vcode")
	public String vcode(HttpServletResponse res) throws IOException {
		InputStream in = RequestContext.get().getCode();
		IOUtils.copy(in, res.getOutputStream());
		return null;
	}

	@RequestMapping("/navigate")
	public String navigate() {
		return "navigate";
	}

	@RequestMapping(value = {"/","/index"})
	public String index(Model model) {
		Cookie cookie = RequestContext.get().getCookie("token");
		if (cookie == null) {
			return "login";
		}
		String token = cookie.getValue();
		Muser user = (Muser)timedCache.get(token);
		if (user == null) {
			user = muserService.getMuser(Long.parseLong(token));
		}
		if (user != null) {
			user.setMenu(muserService.getMenuOne(user));
			timedCache.put(token, user);
			model.addAttribute("time",System.currentTimeMillis()) ;
			return "index";
		}
		return "login";
	}

	@RequestMapping("/tologin")
	public String tologin(HttpServletResponse res, String url, Model model) {
		model.addAttribute("url", url);
		return "login";
	}

	@RequestMapping("/hashlogin")
	public void hashlogin(HttpServletRequest req, HttpServletResponse res, Muser user,
			String url) {
		if ((user = muserService.hashLogin(user)) != null) {
			if (user.getState() != 0) {
				printError(res, "账户已被冻结!");
				return;
			}
			user.setMenu(muserService.getMenuOne(user));
			timedCache.put(Long.toString(user.getToken()), user);
			Cookie cookie = new Cookie("token", Long.toString(user.getToken()));
			cookie.setPath("/");
			String domain = RequestContext.getDomainOfServerName(req.getServerName());
			if (domain != null && domain.indexOf('.') != -1 && !domain.startsWith("127")) {
				cookie.setDomain('.' + domain); // .xytu.com
			}
			cookie.setMaxAge(Integer.MAX_VALUE);
			res.addCookie(cookie);
			printOK(res, "登录成功", url);
			return;
		}
		printError(res, "用户名或密码错误!");
		return;
	}

	@RequestMapping("/hashreg")
	public void hashreg(HttpServletResponse res, HttpSession session, Muser user, String mcode, String url) {
		if (mcode.equals(session.getAttribute("mcode"))) {
			if (muserService.checkname(user.getUname())) {
				user = muserService.addUser(user);
				session.setAttribute("user", user);
				session.removeAttribute("mcode");
				printOK(res, "", url);
				return;
			}

			printError(res, "帐户名已存在!");
			return;
		}
		printError(res, "验证码错误!");
	}

	@RequestMapping("/logout")
	public void logout(HttpServletRequest req, HttpServletResponse res) {
		Cookie cookie = new Cookie("token", null);
		cookie.setPath("/");
		String domain = RequestContext.getDomainOfServerName(req.getServerName());
		if (domain != null && domain.indexOf('.') != -1 && !domain.startsWith("127")) {
			cookie.setDomain('.' + domain); // .xytu.com
		}
		cookie.setMaxAge(0);
		res.addCookie(cookie);
		try {
			res.sendRedirect("/index");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 图片直接保存在服务器固定路径
	 */
	@RequestMapping("/img/in")
	public void imageIn(HttpServletRequest req, HttpServletResponse resp) throws IOException, URISyntaxException{
		String  op = req.getParameter("op") ;
		String  folder = req.getParameter("folder") ;
		MultipartResolver resolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(req);
		if(!StringUtil.hasLength(op))
			op = multipartRequest.getParameter("op") ;
		if(!StringUtil.hasLength(folder))
			folder = multipartRequest.getParameter("folder") ;
		String tp = getFormatDate();
		MultipartFile uoloadimg = multipartRequest.getFile(op);
		int i = uoloadimg.getOriginalFilename().lastIndexOf(".");
		String suf = uoloadimg.getOriginalFilename().substring(i).toLowerCase();
		String  name = randonName() ;
		File filepath = new File(getfile(req, "/data/static/upload") + "/" + folder + "/" + tp);
		if (!filepath.exists())
			filepath.mkdirs();
		File f = new File(filepath + "/" + name+suf );
		copy(uoloadimg.getInputStream(), new FileOutputStream(f));
		if (uoloadimg.getSize() >= (1024 * 1024)) {
			printJSON(resp, "{\"state\":\"001\",\"data\":\"上传的图片不得大于1MB！！！\"}");
			return;
		}
		String fp = "/upload/"+folder+ "/" + tp+ "/" + name+suf ;
		printJSON(resp, "{\"state\":\"000\",\"data\":\""+fp+"\"}");
	}

	private String randonName() {
		return RandomStringUtils.randomAlphabetic(6);
	}

	@RequestMapping("/upload")
	public void upload(HttpServletRequest req, HttpServletResponse resp) throws IOException, URISyntaxException {
		String folder = req.getParameter("folder");
		String op = req.getParameter("op");
		MultipartResolver resolver = new CommonsMultipartResolver(req.getSession().getServletContext());
		MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(req);
		MultipartFile uoloadimg = multipartRequest.getFile(op);
		File filepath = new File(getfile(req, "/data/static/upload") + "/" + folder + "/" + getFormatDate());
		if (!filepath.exists())
			filepath.mkdirs();
		System.out.println(uoloadimg.getOriginalFilename());

		File f = new File(filepath + "/" + uoloadimg.getOriginalFilename());
		copy(uoloadimg.getInputStream(), new FileOutputStream(f));
		// System.out.println("图片大小为：" + uoloadimg.getSize());
		if (uoloadimg.getSize() >= (200 * 1024)) {
			printJSON(resp, "{\"state\":\"001\",\"data\":\"上传的图片不得大于200KB！！！\"}");
			return;
		}
		// printJSON(resp, "{\"state\":\"001\",\"data\":\"/123.png\"}");
		printJSON(resp, remoatUplod(f, folder)); // 上传远程服务
	}

	public static String getFormatDate() {
		return new java.sql.Date(System.currentTimeMillis()).toString().replace("-", "");
	}

	/**
	 * 远程上传到指定的 nginx 服务器
	 * @param file
	 * @param folder
	 * @return
	 * @throws IOException
	 * @throws URISyntaxException
	 */
	public String remoatUplod(File file, String folder) throws URISyntaxException, IOException {
		String url = Constants.apps.get("remoatUpUrl") + "?folder=" + folder;
		AsyncClientHttpRequest request = HttpUtil.createRequest(url, HttpMethod.POST);
		request.getHeaders().add("cookie", "agent=Web; token=-975993958238790062");
		request.getHeaders().add("agent", "Web");
		request.getHeaders().add("token","-975993958238790062");
		request.getHeaders().add("content-type", "application/octet-stream");
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		FileUtil.copy(new FileInputStream(file), out);
		file.delete();
		request.getBody().write(out.toByteArray());
		return HttpUtil.exec(request);
	}

	public void copy(InputStream in, OutputStream out) throws IOException {
		try {
			IOUtils.copy(in, out);
		} finally {
			IOUtils.closeQuietly(in);
			IOUtils.closeQuietly(out);
		}
	}

	public static String getfile(HttpServletRequest request, String uploadpath) {
		File file = new File(uploadpath);
		if (file.isAbsolute()) {
			if (!file.exists())
				file.mkdirs();
			return file.getAbsolutePath();
		}
		file = new File(request.getServletContext().getRealPath("") + file.getPath());
		if (!file.exists())
			file.mkdirs();
		return file.getAbsolutePath();
	}

}
